<template>
  <div class="edu-page-warp">
    <condition-card @reset="resetTaskSubmit" @search="filterTaskSubmit" >
      <el-row :gutter="24" style="height: 50px;">
        <el-col :span="8">
          <el-form-item :label="$t('nonPublicCourseOpen.grade')" >
            <GradeSelect v-model="queryItem.year" style="width: 80%;"></GradeSelect>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="发布状态" >
            <el-select v-model="queryItem.templateStatus" style="width: 80%;">
            <el-option label="全部" value=""></el-option>
            <el-option label="未发布" value="0"></el-option>
            <el-option label="已发布" value="1"></el-option>
            <el-option label="已开始" value="2"></el-option>
          </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </condition-card>
    <!-- <div class="edu-page-title">
      筛选条件
    </div>
    <el-card shadow="never" body-style="padding: 24px;">
      <el-form :inline="true" :model="queryItem" class="demo-form-inline">
        <el-form-item label="年级:" class="no-bottom">
          <el-select v-model="queryItem.year" placeholder="选择年级">
            <el-option v-for="item in serachForm.year" :key="item.value"
                       :label="item.label + '级'"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发布状态:" class="no-bottom">
          <el-select v-model="queryItem.templateStatus" placeholder="发布状态">
            <el-option label="全部" value=""></el-option>
            <el-option label="未发布" value="0"></el-option>
            <el-option label="已发布" value="1"></el-option>
            <el-option label="已开始" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="float-right no-bottom no-right">
          <el-button @click="resetTaskSubmit">重置</el-button>
          <el-button type="primary" @click="filterTaskSubmit">筛选</el-button>
        </el-form-item>
      </el-form>
    </el-card> -->
    <div class="edu-page-title mg-top">
      迎新任务列表
    </div>
    <el-card v-loading="loading" shadow="never" body-style="padding: 24px;">
      <div class="edu-opertion-bar">
        <div class="float-left">
          <el-input
            v-model="queryItem.templateName"
            placeholder="任务名称搜索"
            @change="handSearchChang"
            prefix-icon="el-icon-search"
          >
          </el-input>
        </div>
        <div class="float-right">
          <el-button @click="copyTasksForNew"  v-premit="'copy_task_to'">复制到...</el-button>
          <el-button @click="publishtasks"  v-premit="'publish_task'">发布</el-button>
          <el-button @click="cancelTasks"  v-premit="'cancel_task'">撤销</el-button>
          <el-button @click="deleteTasks"  v-premit="'delete_task'">删除</el-button>
          <el-button @click="addTask" type="primary"  v-premit="'add_task'">新建</el-button>
        </div>
      </div>
      <el-table stripe ref="multipleTable" @select="selectRow" @selection-change="selectionChange" :data="tasks" tooltip-effect="light">
        <edu-table-column
          type="selection"
          width="55"></edu-table-column>
        <edu-table-column prop="oreder" label="顺序" width="55"></edu-table-column>
        <edu-table-column prop="templateName" label="任务名称" >
          <template slot-scope="scope">
            <el-popover trigger="hover" placement="right">
              <span>{{scope.row.templateName}}</span>
              <a slot="reference" type="text" @click="showTaskDetail(scope.row)">
                {{scope.row.templateName}}
              </a>
            </el-popover>

            <!--<a slot="reference" :title="scope.row.templateName" type="text" @click="showTaskDetail(scope.row)">-->
            <!--{{scope.row.templateName}}-->
            <!--</a>-->
          </template>
        </edu-table-column>
        <edu-table-column prop="year" label="年级" width="80px"></edu-table-column>
        <edu-table-column prop="taskTrainingLevelList" label="培养层次" width="160px" >
          <template slot-scope="scope">
            <span>{{ scope.row.trainingLevelsI18n}}</span>
          </template>
        </edu-table-column>
        <edu-table-column prop="isStudentAbroad" label="国际学生" width="80px">
          <template slot-scope="scope">
            <span>{{ scope.row.isStudentAbroad | studentAbroad}}</span>
          </template>
        </edu-table-column>
        <edu-table-column prop="beginTime" label="开始时间" width="140px"  >
          <template slot-scope="scope">
            <span>{{ scope.row.beginTime | formatDate}}</span>
          </template>
        </edu-table-column>
        <edu-table-column prop="endTime" label="结束时间" width="140px" >
          <template slot-scope="scope">
            <span>{{ scope.row.endTime | formatDate}}</span>
          </template>
        </edu-table-column>
        <edu-table-column prop="templateStatus" label="发布状态" width="80px">
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.templateStatus === 0 ? 'info' : 'success'"
              size="mini"
              disable-transitions>{{scope.row.templateStatus | templateStatus}}
            </el-tag>
          </template>
        </edu-table-column>
        <edu-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-button v-premit="'cancel_task'" v-if="scope.row.templateStatus !== 0" type="text" @click="undoTask(scope.row.templateId)"
                       size="mini">撤销
            </el-button>
            <el-button v-premit="'publish_task'" v-if="scope.row.templateStatus === 0" type="text" @click="releaseTask(scope.row.templateId)"
                       size="mini">发布
            </el-button>
            <el-button  v-premit="'edit_task'" v-if="scope.row.templateStatus === 0" type="text" @click="editTask(scope.row.templateId)"
                       size="mini">编辑
            </el-button>
            <el-button v-premit="'copy_task'" type="text" @click="copyTaskForNew(scope.row.templateId)" size="mini">复制</el-button>
            <el-button v-premit="'delete_task'" v-if="scope.row.templateType === 0 && scope.row.templateStatus === 0" type="text"
                       @click="deleteTask(scope.row.templateId)" size="mini">删除
            </el-button>
            <el-button v-premit="'upload_document'" v-if="scope.row.templateType === 1" type="text" @click="uploadFiles(scope.row.templateId)"
                       size="mini">上传
            </el-button>
          </template>
        </edu-table-column>
      </el-table>
      <div class="edu-pagination">
        <!--<div class="float-left">-->
          <!--<span class="edu-total">Total: {{ queryItem.total_ }}</span>-->
        <!--</div>-->
        <div class="float-right">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryItem.pageNum_"
            :page-sizes="[20, 50, 100, 500,1000]"
            :page-size="queryItem.pageSize_"
            layout="total, sizes, prev, pager, next, jumper"
            :total="queryItem.total_"
            style="float:right;margin-top:10px"
          ></el-pagination>
        </div>
      </div>
    </el-card>
    <el-dialog title="复制到..." width="20%" :visible.sync="dailog.copyTask.show">
      <el-form :model="dailog.copyTask.form" inline ref="year">
        <el-form-item label="年级:"
                      prop="year"
                      :rules="[
                        { required: true, message: '请选择年级'}
                      ]">
          <el-select v-model="dailog.copyTask.form.year" placeholder="请选择年级">
            <el-option v-for="item in serachForm.year" :key="item.value"
                       :label="item.label + '级'"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetCopyTask('year')">取 消</el-button>
        <el-button type="primary" @click="copyTaskOk('year')">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="任务详情"
      :visible.sync="showDialog"
      width="50%">
      <TaskPreview class="edu-wel-content" :task-detail="currentTask" :showBtn="showDetaileBtn"/>
      <span slot="footer" class="dialog-footer">
    <el-button @click="showDialog = false">取 消</el-button>
  </span>
    </el-dialog>
  </div>
</template>
<script>
  import {
    getTasks,
    getTasksNoDetail,
    deleteTask,
    releaseTask,
    undoTask,
    copyTask
  } from "common/src/api/welcomeService/taskTemplate";
  import TaskPreview from "common/src/views/tools/TaskPreview";
  import Bus from 'common/src/utils/bus'
  import filters from "common/src/filters";

  export default {
    name: "NewerTasks",
    data() {
      const getGrade = (function() {
        let now = new Date().getFullYear();
        let years = [];
        for (let i = 0; i < 3; i++) {
          years.push({
            label: now + i,
            value: now + i
          });
        }
        return years;
      })();
      return {
        loading: false,
        serachForm: {
          year: getGrade,
          templateStatus: ""
        },
        showDialog: false,
        currentTask: null,
        showDetaileBtn: false,
        multipleSelection: [],
        queryItem: {
          templateId: "",
          year: "",
          templateStatus: "",
          templateName: "",
          pageNum_: 1,
          total_: 0,
          pageSize_: 20
        },
        dailog: {
          copyTask: {
            show: false,
            form: {
              year: '',
              templateIdList: []
            }
          },
          uploadFiles: {
            show: false
          }
        },
        tasks: [],
        functions: []
      };
    },
    components: {
      TaskPreview
    },
    filters: {
      formatDate(date) {
        return filters.formatDate(date, "yyyy/MM/dd hh:mm:ss");
      },
      templateStatus(status) {
        return filters.templateStatus(status);
      },
      taskTrainingLevelList(obj) {
        return filters.taskTrainingLevelList(obj);
      },
      studentAbroad(val) {
        return filters.studentAbroad(val);
      }
    },
    methods: {
      filterTaskSubmit() {
        this.queryItem.pageNum_ = 1;
        this.initPage(this.queryItem);
      },
      resetTaskSubmit() {
        this.queryItem.pageNum_ = 1;
        this.queryItem.year = "";
        this.queryItem.templateStatus = "";
        this.initPage(this.queryItem);
      },
      handSearchChang(string) {
        this.queryItem.templateName = string;
        this.initPage(this.queryItem);
      },
      handleSizeChange(val) {
        this.queryItem.pageSize_ = val;
        this.queryItem.pageNum_ = 1;
        this.initPage(this.queryItem);
      },
      handleCurrentChange(val) {
        this.queryItem.pageNum_ = val;
        this.initPage(this.queryItem);
      },
      handleIconClick() {
      },
      publishtasks() {
        if (this.multipleSelection.length === 0) {
          this.$message({
            message: "你还没有选择任何任务！",
            type: "warning"
          });
          return
        }

        if (_.findIndex(this.multipleSelection, {templateStatus: 0}) === -1) {
          this.$message({
            message: "你还没有选择未发布的任务,不能执行发布操作！",
            type: "warning"
          });
          return
        }

        releaseTask({
          templateIdList: _.map(this.multipleSelection, 'templateId') 
        }).then(res => {
          if (res.code == 200) {
            this.initPage(this.queryItem);
            this.$message({
              message: "恭喜您成功发布任务",
              type: "success"
            });
          } else {
            throw res;
          }
        }).catch((res) => {
          this.$message({
            message: "发布任务失败！",
            type: "error"
          });
        });
      },
      deleteTasks() {
        if (this.multipleSelection.length === 0) {
          this.$message({
            message: "你还没有选择任何任务！",
            type: "warning"
          });
          return
        }

        if (_.findIndex(this.multipleSelection, {templateStatus: 0}) === -1) {
          this.$message({
            message: "你还没有选择未发布的任务,不能执行删除操作！",
            type: "warning"
          });
          return
        }

        this.$confirm("您确定要删除此任务吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            deleteTask({
              templateIdList: _.map(this.multipleSelection, 'templateId')
            }).then(res => {
              if (res.code == 200) {
                this.initPage(this.queryItem);
                this.$message({
                  message: "恭喜您成功删除任务",
                  type: "success"
                });
              }
            })
          })
      },
      cancelTasks() {
        if (this.multipleSelection.length === 0) {
          this.$message({
            message: "你还没有选择任何任务！",
            type: "warning"
          });
          return
        }

       if (_.findIndex(this.multipleSelection, {templateStatus: 1}) === -1) {
          this.$message({
            message: "你还没有选择已发布的任务,不能执行撤销操作！",
            type: "warning"
          });
          return
        }

        this.$confirm("您确定要撤销任务吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          undoTask({
            templateIdList: _.map(this.multipleSelection, 'templateId')
          }).then(res => {
            if (res.code == 200) {
              this.initPage(this.queryItem);
              this.$message({
                message: "恭喜您成功撤销任务",
                type: "success"
              });
            } else {
              throw res;
            }
          }).catch((res) => {
            this.$message({
              message: "撤销任务失败！",
              type: "error"
            });
          });
        }).catch(res=>{});
      },
      addTask() {
        this.$router.push("/createNewerTask");
      },
      editTask(id) {
        this.$router.push("/editNewerTask/" + id);
      },
      copyTaskForNew(id) {
        this.dailog.copyTask.form.templateIdList = [id];
        this.dailog.copyTask.show = true;
      },
      copyTasksForNew() {
        if (this.multipleSelection.length === 0) {
          this.$message({
            message: "你还没有选择任何任务！",
            type: "warning"
          });
          return
        }
        this.dailog.copyTask.form.templateIdList = _.map(this.multipleSelection, 'templateId');
        this.dailog.copyTask.show = true;
      },
      copyTaskOk(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            copyTask(this.dailog.copyTask.form).then(res => {
              if(res && res.code == 200) {
                this.dailog.copyTask.show = false;
                this.initPage(this.queryItem);
                this.$message({
                  message: "恭喜您成功复制任务！",
                  type: "success"
                });
                this.multipleSelection.length = 0;
              } else {
                throw res;
              }
            }).catch(res => {
              this.$message({
                message: "复制任务错误！",
                type: "error"
              });
            });
          } else {
            return false;
          }
        });
      },
      resetCopyTask(formName) {
        this.dailog.copyTask.show = false;
        this.$refs[formName].resetFields();
      },
      deleteTask(id) {
        this.$confirm("您确定要删除此任务吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "error"
        })
          .then(() => {
            deleteTask({
              templateIdList: [id]
            }).then(res => {
              if(res && res.code === 200) {
                this.initPage(this.queryItem);
                this.$message({
                  message: "恭喜您成功删除任务",
                  type: "success"
                });
              } else {
                this.$message({
                  message: res.msg,
                  type: "error"
                });
              }
            }).catch(res => {
              this.$message({
                message: "删除任务失败",
                type: "error"
              });
            });
          })
          .catch(() => {
          });
      },
      cancelTask() {
      },
      showTaskDetail(row) {
        let cloneObj=_.cloneDeep(row)
        cloneObj.beginTime = filters.formatDate(cloneObj.beginTime, "yyyy/MM/dd hh:mm:ss");
        this.showDialog = true;
        this.currentTask = cloneObj;
        // this.$router.push("/createNewerTask/" + id);
      },
      selectRow(selection, row) {
        // this.multipleSelection.push(row.templateId)
        // console.log(this.multipleSelection)
      },
      selectionChange(selection) {
        let self = this;
        self.multipleSelection = selection;
        // selection.forEach(row => {
        //   let index = _.findIndex(this.multipleSelection, row);
        //   if (index == 0) {
        //     self.multipleSelection.push(row);
        //   }
        // });
      },
      copyTo() {
      },
      initPage(options = {}) {
        this.loading = true;
        let query = _.omit(options, ["total"]);
        getTasksNoDetail(query)
          .then(res => {
            if (res.data && res.data.list) {
              this.queryItem.total_ = res.data.total_;
              this.queryItem.pageNum_ = res.data.pageNum_;
              this.queryItem.pageSize_ = res.data.pageSize_;
              this.tasks = res.data.list;
            }
            this.loading = false
          })
          .catch((error) => {
            this.loading = false
          });
      },
      releaseTask(id) {
        releaseTask({
          templateIdList: [id]
        }).then(res => {
          if (res.code == 200) {
            this.initPage(this.queryItem);
            this.$message({
              message: "恭喜您成功发布任务",
              type: "success"
            });
          } else {
            throw res;
          }
        }).catch((res) => {
          this.$message({
            message: "发布任务失败！",
            type: "error"
          });
        });
      },
      undoTask(id) {
        this.$confirm("您确定要撤销此任务吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          undoTask({
            templateIdList: [id]
          }).then(res => {
            if (res.code == 200) {
              this.initPage(this.queryItem);
              this.$message({
                message: "恭喜您成功撤销任务",
                type: "success"
              });
            } else {
              throw res;
            }
          }).catch((res) => {
            this.$message({
              message: "撤销任务失败！",
              type: "error"
            });
          });
        });
      },
      uploadFiles(id) {
        this.$router.push("/UploadFiles/" + id);
      }
    },
    activated() {      
      this.initPage(this.queryItem);
    },
    created() {
      Bus.$on('editSuccess', res => {
        if(res.code === 200) {
          this.initPage(this.queryItem);
        }
      })
    }
  };
</script>

<style>


</style>
